package com.heyu.cgsd.ui.fragment;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;

import com.heyu.cgsd.R;
import com.heyu.cgsd.ui.adapter.BaseRVAdapter;
import com.heyu.cgsd.util.Arith;
import com.heyu.cgsd.util.CalcUtils;
import com.heyu.cgsd.util.DisplayUtils;
import com.heyu.cgsd.util.NumberFormatUtils;

import java.util.ArrayList;
import java.util.List;

public class NormalFragment extends BaseLazyFragment {
    private RecyclerView rv_input;
    private BaseRVAdapter rvAdapter;
    private TextView tv_calc_input;

    private TextView kb_num_ac, kb_num_del, kb_num_divide, kb_num_multiply, kb_num_sub, kb_num_add, kb_num_equal, kb_num_percent, kb_num_dot;
    private TextView kb_num_0, kb_num_1, kb_num_2, kb_num_3, kb_num_4, kb_num_5, kb_num_6, kb_num_7, kb_num_8, kb_num_9;

    private int operateCount;// +,-,*,/次数
    private String curOperate;
    private boolean isEqual;

    private List<String> mData;

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_normal;
    }

    @Override
    protected void initViews(View view) {
        rv_input = view.findViewById(R.id.rv_input);

        kb_num_ac = view.findViewById(R.id.kb_num_ac);
        kb_num_del = view.findViewById(R.id.kb_num_del);
        kb_num_divide = view.findViewById(R.id.kb_num_divide);
        kb_num_multiply = view.findViewById(R.id.kb_num_multiply);
        kb_num_sub = view.findViewById(R.id.kb_num_sub);
        kb_num_add = view.findViewById(R.id.kb_num_add);
        kb_num_equal = view.findViewById(R.id.kb_num_equal);
        kb_num_percent = view.findViewById(R.id.kb_num_percent);
        kb_num_dot = view.findViewById(R.id.kb_num_dot);
        kb_num_0 = view.findViewById(R.id.kb_num_0);
        kb_num_1 = view.findViewById(R.id.kb_num_1);
        kb_num_2 = view.findViewById(R.id.kb_num_2);
        kb_num_3 = view.findViewById(R.id.kb_num_3);
        kb_num_4 = view.findViewById(R.id.kb_num_4);
        kb_num_5 = view.findViewById(R.id.kb_num_5);
        kb_num_6 = view.findViewById(R.id.kb_num_6);
        kb_num_7 = view.findViewById(R.id.kb_num_7);
        kb_num_8 = view.findViewById(R.id.kb_num_8);
        kb_num_9 = view.findViewById(R.id.kb_num_9);
    }

    @Override
    protected void initData() {
        operateCount = 0;
        curOperate = "";
        isEqual = false;

        mData = new ArrayList<>();
        mData.add("");
        mData.add("");
        mData.add("");
        mData.add("");
        mData.add("0");
        mData.add("");

        initAdapter();
    }

    private void initAdapter() {
        rvAdapter = new BaseRVAdapter<String>(mData) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_input;
            }

            @Override
            public void convert(VH holder, String data, int position) {
                tv_calc_input = holder.getView(R.id.item_input);
                tv_calc_input.setText(data);

                if (isEqual) {
                    if (position == mData.size() - 1) {
                        tv_calc_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.sp2px(getActivity(), 48));
                    } else {
                        tv_calc_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.sp2px(getActivity(), 24));
                    }
                } else {
                    if (position == mData.size() - 2) {
                        tv_calc_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.sp2px(getActivity(), 48));
                    } else {
                        tv_calc_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.sp2px(getActivity(), 24));
                    }
                }
                autoMatchFont(tv_calc_input);
            }
        };

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_input.setLayoutManager(linearLayoutManager);

        rv_input.setAdapter(rvAdapter);

//        rvAdapter.setOnItemClickListener(new BaseRVAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(View view, int position) {
//                Toast.makeText(getActivity(), "clicked: " + position, Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    @Override
    protected void initListener() {
        setNormalKeyBoardListener();
    }

    private void setNormalKeyBoardListener() {
        kb_num_0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("0", false);
            }
        });

        kb_num_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("1", false);
            }
        });

        kb_num_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("2", false);
            }
        });

        kb_num_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("3", false);
            }
        });

        kb_num_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("4", false);
            }
        });

        kb_num_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("5", false);
            }
        });

        kb_num_6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("6", false);
            }
        });

        kb_num_7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("7", false);
            }
        });

        kb_num_8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("8", false);
            }
        });

        kb_num_9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("9", false);
            }
        });

        kb_num_dot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput(".", false);
            }
        });

        kb_num_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isEqual) {
                    String str = mData.get(mData.size() - 2);
                    if (str.contains(" ") && str.length() == 3) {
                        if (mData.size() <= 6) {
                            mData.add(0, "");
                        }
                        mData.remove(mData.size() - 2);
                        operateCount--;
                    } else if (str.length() > 3) {
                        str = str.substring(0, str.length() - 1);
                        str = NumberFormatUtils.format(str);
                        mData.set(mData.size() - 2, str);
                    } else {
                        str = "0";
                        mData.set(mData.size() - 2, str);
                    }
                    String last = str.substring(str.length() - 1);
                    if ("E".equals(last)) {
                        mData.set(mData.size() - 2, str.substring(0, str.length() - 1));
                    }
                    calc(mData);
                    rvAdapter.notifyDataSetChanged();
                }
            }
        });

        kb_num_ac.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearInput();
            }
        });

        kb_num_percent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("%", false);
            }
        });

        kb_num_equal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isEqual = true;
                if (!"0".equals(mData.get(mData.size() - 2))) {
                    rvAdapter.notifyDataSetChanged();
                }
            }
        });

        kb_num_divide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"÷".equals(curOperate)) {
                    normalKeyboardInput("÷", true);
                }
            }
        });

        kb_num_multiply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"×".equals(curOperate)) {
                    normalKeyboardInput("×", true);
                }
            }
        });

        kb_num_sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"－".equals(curOperate)) {
                    normalKeyboardInput("－", true);
                }
            }
        });

        kb_num_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"＋".equals(curOperate)) {
                    normalKeyboardInput("＋", true);
                }
            }
        });
    }

    private void normalKeyboardInput(String input, boolean isOperator) {
        if (isEqual) {
            String tmp = mData.get(mData.size() - 1);
            String result = "0";
            if (!"".equals(tmp)) {
                result = tmp.substring(2);
            }
            clearInput();
            if (!isOperator) {
                if ("%".equals(input)) {
                    String str = mData.get(mData.size() - 2);
                    if ("0".equals(str)) {
                        return;
                    }
                }
                if (".".equals(input)) {
                    input = "0.";
                }
                mData.set(mData.size() - 2, input);
                calc(mData);
            } else {
                operateCount++;
                mData.set(mData.size() - 2, result);
                calc(mData);
                mData.add(mData.size() - 1, " " + input + " ");
                moveToPosition(rv_input, mData.size() - 2);
            }
        } else {
            String str = mData.get(mData.size() - 2);
            if (!isOperator) {
                curOperate = "";
                if ("%".equals(input)) {
                    double x;
                    String s1 = "";
                    if ("0".equals(str)) {
                        return;
                    }
                    if (str.contains(" ")) {
                        s1 = str.substring(0, 3);
                        String s = str.substring(3);
                        if ("".equals(s) || "0".equals(s)){
                            return;
                        }
                        x = Double.valueOf(s);
                    } else {
                        x = Double.valueOf(str);
                    }
                    x = Arith.div(x, 100d, 326);

                    mData.set(mData.size() - 2, s1 + x);
                    calc(mData);
                    rvAdapter.notifyDataSetChanged();
                    return;
                }

                if (str.contains(".") && ".".equals(input)) {
                    return;
                } else if (".".equals(input)) {
                    str += input;
                    mData.set(mData.size() - 2, str);
                    rvAdapter.notifyDataSetChanged();
                    return;
                }

                if (str.contains(" ")) {
                    if (str.contains(".") && str.replaceAll(",", "").length() >= 23) {
                        return;
                    }
                    if (!str.contains(".") && str.replaceAll(",", "").length() >= 18) {
                        return;
                    }
                } else {
                    if (str.contains(".") && str.replaceAll(",", "").length() >= 20) {
                        return;
                    }
                    if (!str.contains(".") && str.replaceAll(",", "").length() >= 15) {
                        return;
                    }
                }

                if ("0".equals(str)) {
                    str = input;
                } else {
                    str += input;
                }
                mData.set(mData.size() - 2, NumberFormatUtils.format(str));
                calc(mData);
            } else {
                operateCount++;
                curOperate = input;
                if (str.length() == 3 && str.contains(" ")) {
                    mData.set(mData.size() - 2, " " + input + " ");
                } else if (operateCount < 5) {
                    for (int i = 0; i < mData.size() - 2; i++) {
                        mData.set(i, mData.get(i + 1));
                    }
                    mData.set(mData.size() - 2, " " + input + " ");
                } else {
                    mData.add(mData.size() - 1, " " + input + " ");
                    moveToPosition(rv_input, mData.size() - 2);
                }
            }
        }
        rvAdapter.notifyDataSetChanged();
        isEqual = false;
    }

    private void calc(List<String> list) {
        String s;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size() - 1; i++) {
            s = list.get(i);
//            if (s.contains(",")) {
//                s = s.replaceAll(",", "");
//            }
            if (s.contains(" ") && s.lastIndexOf(" ") == s.length() - 1) {
                break;
            }
            sb.append(s);
        }
        String string = CalcUtils.calc(sb.toString());
        if (!string.contains("不能除以0")) {
            if (!string.contains("E")) {
                string = NumberFormatUtils.format2(string);
            }
        }
        mData.set(mData.size() - 1, "= " + string);
    }

    private void clearInput() {
        operateCount = 0;
        curOperate = "";
        isEqual = false;
        mData.clear();
        mData.add("");
        mData.add("");
        mData.add("");
        mData.add("");
        mData.add("0");
        mData.add("");
        rvAdapter.notifyDataSetChanged();
    }

    private void autoMatchFont(final TextView view) {
        view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                float vWidth = v.getWidth();
                TextPaint paint = view.getPaint();
                String text = view.getText().toString();
                float textLen = paint.measureText(text);
                float oldSize = view.getTextSize();
                if (textLen >= vWidth) {
                    float size = vWidth * oldSize / textLen;
                    view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
                }
            }
        });
    }

    private void moveToPosition(RecyclerView mRecyclerView, int position) {
        if (position != -1) {
            mRecyclerView.scrollToPosition(position);
            LinearLayoutManager mLayoutManager =
                    (LinearLayoutManager) mRecyclerView.getLayoutManager();
            mLayoutManager.scrollToPositionWithOffset(position, 0);
        }
    }
}
